package com.czy.contorller.admin;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.czy.dto.AddAssetDto;
import com.czy.dto.AssetExportDto;
import com.czy.dto.AssetPageDto;
import com.czy.result.Result;
import com.czy.service.AssetService;
import com.czy.vo.AdminAssetPageVo;
import com.czy.vo.PageVo;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;

@Slf4j
@RestController
@RequestMapping("/admin/asset")
public class AdminAssetController {

    @Autowired
    private AssetService assetService;

    // 管理员端分页查询资产表
    @GetMapping("/list")
    public Result<PageVo> list(AssetPageDto assetPageDto) {
        log.info("分页查询数据：{}", assetPageDto);
        PageVo vo = assetService.list(assetPageDto);
        return Result.success(vo);
    }

    //新增资产
    @PostMapping("/add")
    public Result addAsset(@RequestBody AddAssetDto addAssetDto) {
        log.info("要新增的资产信息：{}", addAssetDto);
        assetService.addAsset(addAssetDto);
        return Result.success();
    }

    //删除资产
    @DeleteMapping
    public Result deleteAsset(@RequestParam ArrayList<Integer> ids) {
        log.info("删除资产的id：{}", ids);
        assetService.deleteAsset(ids);
        return Result.success();

    }

    //根据id查询资产信息
    @GetMapping("/detail/{id}")
    public Result<AdminAssetPageVo> findById(@PathVariable Long id) {
        log.info("要查的资产id：{}", id);
        AdminAssetPageVo vo = assetService.findById(id);
        return Result.success(vo);
    }

    //导出资产信息
    //这里有严重问题
//    @PostMapping("/export")
//    public void AssetExportExcel(@RequestBody AssetPageDto assetPageDto,HttpServletResponse response) throws IOException {
//
//        log.info("为什么这种接收：{}",assetPageDto);
//        log.info("请求头：{}" , response);
//
//        // 1. 设置响应头（与前端代码对应）
//        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//        response.setCharacterEncoding("utf-8");
//        String fileName = URLEncoder.encode("资产列表", "UTF-8").replaceAll("\\+", "%20");
//        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
//
//        //查询数据
//        PageVo list = assetService.list(assetPageDto);
//
//        // 3. 导出Excel（带自动列宽）
//        EasyExcel.write(response.getOutputStream(), AssetExportDto.class)
//                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) // 自动列宽
//                .sheet("资产明细")
//                .doWrite(list.getRecords());
//    }
}
